from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import pyqtSignal, QTimer
from PyQt5.QtGui import QImage, QPixmap
from ui_login import Ui_WindowLogin
from ui_main import Ui_WindowMain
import database_operations
import sys, cv2


class WindowLogin(QMainWindow, Ui_WindowLogin):
    # 登陆成功信号
    login_successful = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setFixedSize(self.size())
        self.init()

    def init(self):
        # 登录按钮绑定事件
        self.pushButton_Login.clicked.connect(self.login)
        self.pushButton_Register.clicked.connect(self.register)

    def login(self):
        username = self.lineEdit_Username.text()
        password = self.lineEdit_Password.text()
        # 账号密码验证逻辑
        if username != '' and password != '':
            state, power = database_operations.login(username=username, password=password)
            if state:
                if power == 0:
                    self.label.setStyleSheet("color: red;")
                    self.label.setText('用户权限不足')
                else:
                    # 暂时除了0都可以登录
                    self.login_successful.emit()
                    self.close()
            else:
                self.label.setStyleSheet("color: red;")
                self.label.setText('用户名或密码错误')
        else:
            self.label.setStyleSheet("color: red;")
            self.label.setText('用户名或密码不能为空')

    def register(self):
        username = self.lineEdit_Username.text()
        password = self.lineEdit_Password.text()
        # 账号密码验证逻辑
        if username != '' and password != '':
            stateStr = database_operations.register(username=username, password=password)
            if stateStr == 'success':
                self.label.setStyleSheet("color: green;")
                self.label.setText('注册成功')
            elif stateStr == 'registered':
                self.label.setStyleSheet("color: red;")
                self.label.setText('用户已被注册')
            else:
                self.label.setStyleSheet("color: red;")
                self.label.setText('注册失败')
        else:
            self.label.setStyleSheet("color: red;")
            self.label.setText('用户名或密码不能为空')


class WindowMain(QMainWindow, Ui_WindowMain):
    def __init__(self):
        super().__init__()
        # 初始化摄像头
        self.cap = cv2.VideoCapture()
        # 初始化定时器
        self.timer_camera = QTimer()
        self.timer_clear = QTimer()
        # 初始化图片
        self.showImage = QImage()

        self.setupUi(self)
        self.init()

    def init(self):
        self.label.setStyleSheet("color: red;")
        # 图片自适应
        self.label1.setScaledContents(True)
        self.label2.setScaledContents(True)
        self.timer_camera.timeout.connect(self.show_image)
        # 打开摄像头
        self.pushButton_OpenCamera.clicked.connect(self.open_camera)
        self.pushButton_CloseCamera.clicked.connect(self.close_camera)
        self.pushButton_TakePic.clicked.connect(self.take_pic)
        self.pushButton_ClearPic.clicked.connect(self.clear_pic)

    def open_camera(self):
        if not self.timer_camera.isActive():
            self.cap = cv2.VideoCapture(0)
            # 每40毫秒读取一次  刷新率为25帧
            self.timer_camera.start(40)
            self.show_image()
        else:
            print('摄像头已打开')

    def close_camera(self):
        if self.timer_camera.isActive():
            self.timer_camera.stop()
            self.cap.release()
            self.label1.clear()
            self.label1.setText("摄像头")
        else:
            print('摄像头未打开')

    def show_image(self):
        # 从视频流中读取图片
        flag, image = self.cap.read()
        image_show = cv2.resize(image, (1280, 720))
        width, height = image_show.shape[:2]
        image_show = cv2.cvtColor(image_show, cv2.COLOR_BGR2RGB)
        # 水平翻转  因为摄像头拍的是镜像的
        # image_show = cv2.flip(image_show, 1)
        # 把读取到的视频数据变成QImage形式
        self.showImage = QImage(image_show.data, height, width, QImage.Format_RGB888)
        self.label1.setPixmap(QPixmap.fromImage(self.showImage))

    def take_pic(self):
        if self.cap.isOpened():
            self.label2.setPixmap(QPixmap.fromImage(self.showImage))
            self.label.setText('拍照成功')

            self.timer_clear.singleShot(4000, self.clear_pic)
            # 保存图片
            # self.showImage.save('./1.jpg')
        else:
            self.label.setText('摄像头未打开')
            print('摄像头未打开')

    def clear_pic(self):
        self.label2.clear()
        self.label.setText('照片清除成功')



def main():
    app = QApplication(sys.argv)
    window_login = WindowLogin()
    window_main = None

    def show_main_window():
        nonlocal window_main
        window_main = WindowMain()
        window_main.show()

    # 把登录页的信号绑定上触发事件
    window_login.login_successful.connect(show_main_window)
    window_login.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
